package com.android.corestat.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年4月17日
 * @version 1.0
 */

public class MemUtils {
	private static final String TAG = MemUtils.class.getSimpleName();

	public static String getCpuInfo() {
		String str = null;

		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("/proc/cpuinfo");
			if (fr != null)
				try {
					br = new BufferedReader(fr, 1024);
					str = br.readLine();
					br.close();
					fr.close();
				} catch (IOException ex) {
					Log.w(TAG, "Could not read from file /proc/cpuinfo", ex);
				}
		} catch (FileNotFoundException ex) {
			Log.w(TAG, "Could not open file /proc/cpuinfo", ex);
		}

		if (str != null) {
			int i = str.indexOf(':') + 1;
			str = str.substring(i);
		}
		return str.trim();
	}

	/**
	 * 获取系统RAM的总空间及剩余空间
	 * 
	 * @return long[0]:total<br>
	 *         long[1]:free
	 */
	public static long[] getRamInfo() {
		long[] ret = new long[2];
		boolean total = false, free = false;

		String meminfo = "/proc/meminfo";
		String line = null;
		try {
			FileReader fr = new FileReader(meminfo);
			BufferedReader br = new BufferedReader(fr, 8192);
			while ((line = br.readLine()) != null) {
				if (total && free) {
					break;
				}

				if (line.startsWith("MemTotal")) {
					ret[0] = extractMemValue(line);
					total = true;
				}
				if (line.startsWith("MemFree")) {
					ret[1] = extractMemValue(line);
					free = true;
				}
			}
			br.close();

		} catch (IOException e) {
			Log.e(TAG, "", e);
		}
		return ret;
	}

	private static long extractMemValue(String line) {
		String[] ss = line.split(":");
		if (ss == null || ss.length != 2) {
			return 0;
		}
		ss[1].trim();// 101 KB
		String val = ss[1].trim();
		val = val.substring(0, val.length() - 3);
		return Long.valueOf(val) * 1024;
	}

	public static long[] getRomInfo() {
		String path = Environment.getDataDirectory().getPath();
		StatFs statFs = new StatFs(path);
		long blockSize = statFs.getBlockSize();
		long totalBlocks = statFs.getBlockCount();
		long availableBlocks = statFs.getAvailableBlocks();

		// 处理存储容量格式
		long[] ret = new long[2];
		ret[0] = totalBlocks * blockSize;
		ret[1] = availableBlocks * blockSize;
		return ret;
	}

}
